package Card.view;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import Card.connect.CardClient;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;

/*
 * The window for connect this client to server we set.
 * @author Juthamas Utamaphethai 5510546964
 * @author Natcha Chidbhob 5510546026
 */
public class Connect extends JFrame {
	/** The client who going to join the game. */
	private CardClient client;
	/** Showing host. */
	private JLabel host;
	/** Text to type IP of host. */
	private JTextField text;
	/** Connect button. */
	private JButton connect;

	/*
	 * Initialize the frame and window.
	 */
	public Connect() {
		super("Connect");
		initComponents();
	}

	/*
	 * initial all components in frame.
	 */
	private void initComponents() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		ClassLoader cldr = this.getClass().getClassLoader();
		java.net.URL imageURL = cldr.getResource("bg/connect.png");
		ImageIcon pic = new ImageIcon(imageURL);
		ImagePanel pane = new ImagePanel(pic.getImage());

		pane.setLayout(new FlowLayout());
		host = new JLabel("Host : ");
		host.setFont(new Font("Tahoma", Font.BOLD, 16));
		host.setForeground(new Color(0, 0, 0));
		host.setBackground(Color.WHITE);
		text = new JTextField();
		text.setBackground(new Color(255, 255, 255));
		text.setColumns(10);
		connect = new JButton("CONNECT");
		connect.setForeground(new Color(0, 0, 204));
		connect.setFont(new Font("Tahoma", Font.BOLD, 12));
		connect.setBackground(new Color(204, 204, 255));
		connect.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				client = new CardClient(text.getText(), 111);
				try {
					client.openConnection();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				if (client.isConnected()) {
					LoginUI login = new LoginUI(client);
					client.addObserver(login);
					login.run();
					dispose();
				}

			}
		});
		pane.add(host);
		pane.add(text);
		pane.add(connect);
		getContentPane().add(pane);

	}

	/*
	 * Run up the window.
	 */
	public void run() {
		pack();
		setSize(300, 73);
		setResizable(false);
		setVisible(true);
	}

	/*
	 * Make new connection window and run it up.
	 */
	public static void main(String[] args) {
		Connect connect = new Connect();
		connect.run();
	}

}
